<template>
  <div class="search_id">
    <div class="title"><span>角色管理</span></div>
    <el-container>
      <el-main>
        <!-- 查询start -->
        <div style="float: left">
          <el-form
            :model="formInline"
            ref="formInlineRef"
            :inline="true"
            class="demo-form-inline"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="formInline.roleName"
                placeholder="请输入角色名称"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit(formInline)"
                ><i class="el-icon-search"></i>查询</el-button
              >
              <el-button @click="resetForm('formInlineRef')"
                ><i class="el-icon-refresh-left"></i>重置</el-button
              >
            </el-form-item>
          </el-form>
          <!-- <el-button @click="toggleSelection([tableData[1], tableData[2]])"
            >切换第二、第三行的选中状态</el-button
          >
          <el-button @click="toggleSelection()">取消选择</el-button> -->
        </div>
        <!-- 查询end  -->
        <el-col>
          <div style="float: left">
            <el-button
              type="primary"
              @click="dialogFormVisible = true"
              size="small"
              plain
              ><i class="el-icon-plus"></i>新增</el-button
            >
            <el-button
              type="danger"
              @click="DelListCar(delList)"
              size="small"
              plain
              ><i class="el-icon-delete"></i>删除</el-button
            >
          </div>
        </el-col>

        <!-- 添加start -->
        <el-dialog title="新增货主" :visible.sync="dialogFormVisible">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="110px"
            class="demo-ruleForm"
          >
            <el-form-item label="角色名称" required>
              <el-col :span="11">
                <el-input
                  v-model="ruleForm.OwnerOfCargoName"
                  placeholder="请输入角色名称"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="上级名称" required>
              <el-col :span="11">
                <el-select v-model="value" placeholder="请选择上级名称">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="别名" required>
              <el-col :span="11">
                <el-input
                  v-model="ruleForm.OwnerOfCargoPhone"
                  placeholder="请输入角色别名"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCar(ruleForm)"
              >确 定</el-button
            >
          </div>
        </el-dialog>
        <!-- 添加end -->

        <!-- 修改start -->
        <el-dialog title="修改车辆" :visible.sync="dialogFormVisibleEdit">
          <el-form
            :model="ruleFormEdit"
            status-icon
            :rules="rules"
            ref="ruleFormEdit"
            label-width="110px"
            class="demo-ruleForm"
          >
            <el-form-item label="角色名称" required>
              <el-col :span="11">
                <el-input
                  v-model="ruleFormEdit.OwnerOfCargoName"
                  placeholder="请输入角色名称"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="上级名称" required>
              <el-col :span="11">
                <el-select v-model="value" placeholder="请选择上级名称">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="别名" required>
              <el-col :span="11">
                <el-input
                  v-model="ruleFormEdit.OwnerOfCargoPhone"
                  placeholder="请输入角色别名"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
            <el-button type="primary" @click="UpdCar(ruleFormEdit)"
              >确 定</el-button
            >
          </div>
        </el-dialog>
        <!-- 修改end -->

        <!-- 显示start -->
        <el-table
          ref="multipleTable"
          :data="
            tableData.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          tooltip-effect="dark"
          style="width: 100%; text-align: center"
          border
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleCreateName" label="上级角色">
          </el-table-column>
          <el-table-column prop="roleMsg" label="别名"></el-table-column>
          <el-table-column prop="roleCreateTime" label="创建时间">
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="
                  (dialogFormVisibleEdit = true), EditCar(scope.row.roleID)
                "
                ><i class="el-icon-edit"></i>编辑</el-button
              >
              <el-button
                type="text"
                size="small "
                @click="SingledelCar(scope.row.roleID)"
                ><i class="el-icon-close"></i>删除</el-button
              >
              <el-button
                @click="handleClick(scope.row.roleID)"
                type="text"
                size="small"
                ><i class="el-icon-success"></i>分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 显示end -->
        <!-- 分页start -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        >
        </el-pagination>
        <!-- 分页ends -->
        <el-dialog title="菜单权限" :visible.sync="dialogTableVisible">
          <div style="height: 70%">
            <el-tree
              :data="data"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              highlight-current
              :props="defaultProps"
            >
            </el-tree>
          </div>
          <div class="buttons">
            <el-button @click="getCheckedKeys(data)">分配权限</el-button>
            <el-button @click="resetChecked">清空</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "vehicle",
  data() {
    return {
      //表单数据
      tableData: [], //显示
      delList: [], //被选中的记录数据
      ids: [], //批量删除ID
      //分页
      currentPage: 1, //当前页码
      total: 0, //总条数
      pageSize: 5, //每页数据条
      //查询
      formInline: {
        roleName: "",
      },
      //添加
      dialogTableVisible: false,
      dialogFormVisible: false, //添加模态框
      dialogFormVisibleEdit: false, //反填模态框
      //添加
      ruleForm: {
        OwnerOfCargoName: "",
        OwnerOfCargoPhone: "",
        CompanyName: "",
        ContactAddress: "",
        DrivingLicenceTime: "",
        DrivingLicenceImg: "",
        Remark: "",
      },
      options: [
        {
          value: "选项1",
          label: "黄金糕",
        },
        {
          value: "选项2",
          label: "双皮奶",
        },
        {
          value: "选项3",
          label: "蚵仔煎",
        },
        {
          value: "选项4",
          label: "龙须面",
        },
        {
          value: "选项5",
          label: "北京烤鸭",
        },
      ],
      value: "",
      //编辑
      ruleFormEdit: {
        ownerOfCargoID: "",
        ownerOfCargoName: "",
        ownerOfCargoPhone: "",
        companyName: "",
        contactAddress: "",
        drivingLicenceTime: "",
        drivingLicenceImg: "",
        remark: "",
      },
      formLabelWidth: "120px",
      rules: {
        // //验证
        // FactoryPlateModel: [
        //   { required: true, message: "请输入厂牌型号", trigger: "blur" },
        // ],
        // LicensePlateNumber: [
        //   { required: true, message: "请输入车牌号", trigger: "blur" },
        // ],
        // LicensePlateName: [
        //   { required: true, message: "请输入司机名称", trigger: "blur" },
        // ],
        // LicensePlateLWH: [
        //   {
        //     required: true,
        //     message: "请输入车型（长*宽*高）",
        //     trigger: "blur",
        //   },
        // ],
        // LicensePlateColour: [
        //   { required: true, message: "请输入颜色", trigger: "blur" },
        // ],
        // ServiceCertificateNumber: [
        //   { required: true, message: "请输入运营证号", trigger: "blur" },
        // ],
        // MaintainKilometreSetting: [
        //   { required: true, message: "请输入保养公里设置", trigger: "blur" },
        // ],
        // InsuranceExpireTime: [
        //   {
        //     type: "date",
        //     required: true,
        //     message: "请选择日期",
        //     trigger: "change",
        //   },
        // ],
        // AnnualExpireTime: [
        //   {
        //     type: "date",
        //     required: true,
        //     message: "请选择日期",
        //     trigger: "change",
        //   },
        // ],
        // BuyTime: [
        //   {
        //     type: "date",
        //     required: true,
        //     message: "请选择日期",
        //     trigger: "change",
        //   },
        // ],
      },
      //上传图片
      DrivingLicenceImg: "",
      dialogVisible: false,
      //索引
      vehicleIndex: 0,
      //树形控件
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      menu_ID: [],//树形菜单Id
      roleId:"",//获取角色Id
      role_menu_ID:[],
    };
  },
  created() {
    //商品显示
    this.GetList();
    this.GetTree();
  },
  inject: ["reload"], //注入
  methods: {
    //查看
    handleClick(row) {
      this.roleId=row;//赋给角色Id
      console.log(this.roleId);//打印角色Id
      this.dialogTableVisible = true;//打开模态框
      //反填该角色已有的菜单
      this.axios
        .get("MenuAPI/Menu_ID?roleID=" + row)
        .then((res) => {
          this.menu_ID = res.data.body;
          //反填树形菜单
          this.$refs.tree.setCheckedKeys(this.menu_ID);
        });
    },
    //显示树形菜单
    GetTree() {
      this.axios.get("MenuAPI/Tree").then((res) => {
        this.data = res.data.body;
      });
    },
    //树形控件 分配权限
    getCheckedKeys(data) {
      console.log(this.$refs.tree.getCheckedKeys(JSON.stringify(data.id)));
      this.role_menu_ID=this.$refs.tree.getCheckedKeys(JSON.stringify(data.id));

      if (this.role_menu_ID==null||this.role_menu_ID==""){
          this.$message.error("还没有分配，请分配权限");
          this.dialogTableVisible = false; //关闭模态框
          this.reload(); //局部刷新
          return;
      }
      //执行
      this.axios({
        url: "MenuAPI/AddRoleMenu?roleId="+this.roleId+"&intList="+this.role_menu_ID,
        method: "post",
      }).then((res) => {
        console.log(res.data.code);
        if (res.data.code == 200) {
          this.$message.success("添加成功");
          this.dialogTableVisible = false; //关闭模态框
          this.reload(); //局部刷新
        } else {
          this.$message.error("添加失败");
          this.dialogTableVisible = false; //关闭模态框
          this.reload(); //局部刷新
        }
      });
    },
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([34, 41, 52]);
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    //全选
    handleSelectionChange(val) {
      console.log("handleSelectionChange--", val);
      this.delList = val; //把将要删除的数据存进集合中
    },
    // 分页
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    //查询
    onSubmit(formInline) {
      this.axios
        .get(
          "RoleAPI/GetRoles?roleName=" +
            formInline.roleName +
            ""
        )
        .then((res) => {
          this.tableData = res.data.data;
          this.total = res.data.count;
          console.log(res.data);
        });
    },
    //重置
    resetForm(formInlineRef) {
      this.$refs[formInlineRef].resetFields();
    },
    //显示
    GetList() {
      this.axios
        .get("RoleAPI/GetRoles")
        .then((res) => {
          this.tableData = res.data.data;
          this.total = res.data.count;
          console.log(res.data);
        });
    },
    //添加
    addCar(ruleForm) {
      console.log(ruleForm);
      this.axios({
        url: "OwnerOfCargoAPI/AddOwner",
        method: "post",
        data: ruleForm,
      }).then((res) => {
        if (res.data.meta == 200) {
          this.$message.success("添加成功");
          this.dialogFormVisible = false; //关闭模态框
          this.reload(); //局部刷新
        } else {
          this.$message.error("添加失败");
          this.dialogFormVisible = false; //关闭模态框
          this.reload(); //局部刷新
        }
      });
    },
    //单删
    SingledelCar(registrationID) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios({
            url:
              "OwnerOfCargoAPI/DelOwner?id=" +
              registrationID,
            method: "post",
          }).then((res) => {
            console.log(res);
            if (res.data.meta == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.reload(); //局部刷新
            } else {
              this.$message.error("删除失败");
              this.reload(); //局部刷新
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //反填模态框
    EditCar(item) {
      this.dialogFormVisibleEdit == true;
      this.axios
        .get("OwnerOfCargoAPI/EditOwner?id=" + item)
        .then((res) => {
          console.log(res.data.data);
          this.ruleFormEdit = res.data.data;
        });
    },
    //修改车辆
    UpdCar(ruleFormEdit) {
      console.log(ruleFormEdit);
      this.axios({
        url: "OwnerOfCargoAPI/UpdOwner",
        method: "post",
        data: ruleFormEdit,
      }).then((res) => {
        if (res.data.meta == 200) {
          this.$message.success("修改成功");
          this.dialogFormVisible = false; //关闭模态框
          this.reload(); //局部刷新
        } else {
          this.$message.error("修改失败");
          this.dialogFormVisible = false; //关闭模态框
          this.reload(); //局部刷新
        }
      });
    },
    //批量删除
    DelListCar(rows) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //循环获取要删除的Id并存进数组中
          rows.forEach((element) => {
            this.ids.push(element.ownerOfCargoID);
          });
          // console.log(JSON.stringify(this.ids));
          // console.log(JSON.stringify(this.ids).length);
          //删除ID数组
          var num = JSON.stringify(this.ids).substring(
            1,
            JSON.stringify(this.ids).length - 1
          ); //装换成json格式在截取
          console.log(num);
          //Ajax执行删除
          this.axios({
            url: "OwnerOfCargoAPI/DelOwner?id=" + num,
            method: "post",
          }).then((res) => {
            console.log(res.data);
            if (res.data.meta == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.reload(); //局部刷新
            } else {
              this.$message.error("删除失败！");
              this.reload(); //局部刷新
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style scoped>
.search_id {
  width: 100%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.title {
  width: 100%;
  height: 50px;
  background-color: #f3f3f3;
}
.title span {
  float: left;
  padding-top: 15px;
  color: #999999;
  margin-left: -80px;
}
/* /deep/.el-table th > .cell {
  text-align: center;
}

/deep/.el-table .cell {
  text-align: center;
} */
</style>